<script setup>
// import HelloWorld from './components/HelloWorld.vue'
import OpenAI from "openai";

// const apiKey = 'sk-91597582d56a47519f3d4f03d8314d98';
const apiKey = 'MBBPBPIR78XPJMYOZPUHSJMY2XLNG65X0PIQKFQI';
const openai = new OpenAI({
        // baseURL: 'https://api.deepseek.com',
        baseURL: "https://ai.gitee.com/v1",
        apiKey: apiKey,
        dangerouslyAllowBrowser: true,
        defaultHeaders: {"X-Failover-Enabled":"true","X-Package":"1910"},
});
// console.log(openai);

async function main() {
  let isStream = true
  const completion = await openai.chat.completions.create({
    // messages: [{ role: "system", content: "You are a helpful assistant." }],
    // model: "deepseek-chat",
    model: "DeepSeek-R1-Distill-Qwen-32B",
    stream: isStream,
    max_tokens: 1024,
    temperature: 0.6,
    top_p: 0.8,
    top_k: 20,
    frequency_penalty: 1.1,
    messages: [
      {
        "role": "system",
        "content": "随便说一个数字"
      },
      {
        "role": "user",
        "content": "告诉我你的姓名"
      }
    ],
  });

  // console.log(completion.choices[0].message.content);
  // console.log(completion); // stream:false的时候打印才有效果
  if(isStream) {
    // 获取可读流
    const reader = completion.body.getReader();
    const decoder = new TextDecoder('utf-8');
    let done = false;

    while (!done) {
        const { value, done: doneReading } = await reader.read();
        done = doneReading;
        const chunk = decoder.decode(value, { stream: !done });
        const lines = chunk.split('\n').filter(line => line.trim() !== '');

        for (const line of lines) {
            if (line.startsWith('data: ')) {
                const message = line.replace(/^data: /, '');
                if (message === '[DONE]') {
                    done = true;
                    break;
                }
                try {
                    const parsed = JSON.parse(message);
                    if (parsed.choices && parsed.choices[0] && parsed.choices[0].delta && parsed.choices[0].delta.content) {
                        const content = parsed.choices[0].delta.content;
                        const outputElement = document.getElementById('output');
                        outputElement.innerHTML += content;
                    }
                } catch (error) {
                    console.error('Error parsing JSON:', error);
                }
            }
        }
    }
  }
  
}
async function main2() {
  let isStream = true;

  const response = await fetch('https://ai.gitee.com/v1/chat/completions', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${apiKey}`, // 替换为你的 API 密钥
      // 'Authorization': apiKey, // 替换为你的 API 密钥
    },
    body: JSON.stringify({
      model: "DeepSeek-R1-Distill-Qwen-32B",
      stream: isStream,
      max_tokens: 1024,
      temperature: 0.6,
      top_p: 0.8,
      top_k: 20,
      frequency_penalty: 1.1,
      messages: [
        {
          "role": "system",
          "content": "随便说一个数字"
        },
        {
          "role": "user",
          "content": "告诉我你的姓名"
        }
      ],
    }),
  });

  const reader = response.body.getReader();
  const decoder = new TextDecoder();
  const output = document.getElementById('output');
  const think = document.getElementById('think');
  let t_end = false
  while (true) {
    const { done, value } = await reader.read();
    if (done) break;

    const chunk = decoder.decode(value);
    const lines = chunk.split('\n');

    for (const line of lines) {
      if (line.trim() === '') continue;

      const data = line.replace('data: ', '');
      if (data === '[DONE]') {
        console.log('Stream completed');
        return;
      }

      try {
        const parsedData = JSON.parse(data);
        const content = parsedData.choices[0].delta.content;
        if (content) {
          if(content === '</think>') { // 思考结束
            console.log('思考结束1');
            t_end = true
          }
          console.log(content); // 处理每一块数据
          if(!t_end) {
            think.innerHTML += content;
          } else {
            console.log('思考结束2');
            output.innerHTML += content;
          }
        }
      } catch (error) {
        console.error('Error parsing JSON:', error);
      }
    }
  }
}
// 调用函数
function handleClick() {
  main2();
}
</script>

<template>
  <!-- <div>
    <a href="https://vite.dev" target="_blank">
      <img src="/vite.svg" class="logo" alt="Vite logo" />
    </a>
    <a href="https://vuejs.org/" target="_blank">
      <img src="./assets/vue.svg" class="logo vue" alt="Vue logo" />
    </a>
  </div> -->
  <!-- <HelloWorld msg="Vite + Vue" /> -->
  <div>
    <button @click="handleClick">Click me</button>
  </div>
  <div class="think" id="think"></div>
  <div class="output" id="output"></div>
</template>

<style scoped>
.logo {
  height: 6em;
  padding: 1.5em;
  will-change: filter;
  transition: filter 300ms;
}
.logo:hover {
  filter: drop-shadow(0 0 2em #646cffaa);
}
.logo.vue:hover {
  filter: drop-shadow(0 0 2em #42b883aa);
}
.think{
  text-align: left;
    /* color: #000000; */
    /* opacity: .5; */
    border: 1px solid #ffffff;
    padding: 20px;
    margin: 20px;
    color: #ffffff63;
}
</style>
